package com.crazydream.wechat.security.handler;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.crazydream.wechat.common.utils.CommonUtil;
import com.crazydream.wechat.system.model.User;
import com.crazydream.wechat.system.service.UserService;

/**
 * spring security登录成功处理
 * 
 * @author shadow
 * @email 124010356@qq.com
 * @create 2012.04.28
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	private UserService userService;

	private String successUrl; // 登陆成功跳转路径

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getSuccessUrl() {
		return successUrl;
	}

	public void setSuccessUrl(String successUrl) {
		this.successUrl = successUrl;
	}

	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		this.userService.LoginForUpdate(getUpdateVO(user, request));
		request.getRequestDispatcher(successUrl).forward(request, response);
	}

	private User getUpdateVO(User user, HttpServletRequest request) {
		user.setLastip(CommonUtil.getClientIP(request));
		user.setLogincount(user.getLogincount()+1);
		user.setLastdate(new Date());
		return user;
	}
}
